<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkEmployee\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Tenant\Contract\TenantContract;
use MoChat\App\User\Contract\UserContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use Qbhy\HyperfAuth\AuthManager;
use Qbhy\SimpleJwt\JWTManager;

/**
 * 查询 - 列表.
 * @Controller
 */
class StatusUpdate extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var AuthManager
     */
    protected $authManager;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    private $workEmployeeService;

    /**
     * @Inject
     * @var TenantContract
     */
    private $tenantService;

    /**
     * @Inject
     * @var UserContract
     */
    private $userService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workEmployee/statusUpdate", methods="PUT")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }

        $corpId = (int) $user['corpIds'][0];

        // 请求参数
        $params = $this->request->inputs(['id', 'status']);

        // 校验参数
        $this->validated($params);

        $employee = $this->workEmployeeService->getWorkEmployeeById((int) $params['id']);

        if (empty($employee)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '员工不存在');
        }

        if ($employee['corpId'] != $corpId) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '您没有权限修改该员工');
        }

        if (empty($employee['mobile']) && $params['status'] == 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '员工手机为空，无法开通坐席，请员工前往企业微信填写手机号');
        }

        $tenant = $this->tenantService->getTenantById((int) $user['tenantId']);
        if (empty($tenant)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '租户不存在');
        }

        $useEmployee = $this->workEmployeeService->countOpenedWorkEmployeeByCorpId($corpId);

        if ($useEmployee >= $tenant['maxEmployee'] && $params['status'] == 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '坐席数量已满，无法开通坐席');
        }

        $employeeData['auth_status'] = $params['status'];
        if ($params['status'] == 1) {
            $userData['status'] = 1;
        } else {
            $userData['status'] = 3;
        }

        if (! empty($employee['logUserId'])) {
            $this->userService->updateUserById((int) $employee['logUserId'], $userData);
        }

        $userInfo = $this->userService->getUserByPhone($employee['mobile'], ['id']);

        if (! empty($userInfo)) {
            $employeeData['log_user_id'] = $userInfo['id'];
        } else {
            if ($params['status'] == 1) {
                $guard = $this->authManager->guard('jwt');
                /** @var JWTManager $jwt */
                $jwt = $guard->getJwtManager();
                $password = $jwt->getEncrypter()->signature(substr(md5(mt_rand(0, 32) . '0905' . md5((string) mt_rand(0, 32)) . '0123'), 10, 6));

                $createUserData = [
                    'phone' => $employee['mobile'],
                    'password' => $password,
                    'name' => $employee['name'] ?? '',
                    'gender' => $employee['gender'] ?? 0,
                    'department' => $employee['main_department_id'] ?? 0,
                    'position' => $employee['position'] ?? '',
                    'tenant_id' => $user['tenantId'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'status' => $userData['status'],
                ];

                // 创建子账户
                $this->userService->createUser($createUserData);
            }
        }

        // 修改坐席授权状态
        $this->workEmployeeService->updateWorkEmployeeById((int) $params['id'], $employeeData);

        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'status' => 'integer | required',
            'id' => 'integer | required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'status.integer' => '员工状态必须为整数',
            'status.required' => '员工状态必填',
            'id.integer' => '员工ID必须为整数',
            'id.required' => '员工ID必填',
        ];
    }
}
